const Koa = require('koa');
const body = require('koa-better-body');
const session = require('koa-session');
const Router = require('koa-router');
const onerror = require('koa-onerror');
const logger = require('koa-logger')
// const { logger, accessLogger } = require('./libs/logger');


const path = require('path');
const fs = require('fs');

const _static = require('./routes/static');
const db = require('./libs/database.js')
// const logger = require('./libs/logger.js')


const app = new Koa();

app.listen(9999, () => {
	console.log(`服务器启动在9999端口`)
});
// 数据库连接
app.context.db = db;

// 处理错误
onerror(app);

// logger
app.use(logger((str, args) => { }))
// logger(app);自家写的
// app.use(accessLogger());

// 请求数据处理
app.use(body({
	uploadDir: path.resolve(__dirname, './static/upload'),
	keepExtensions: true
}))



// sesstion
app.use(session({
	maxAge: 20 * 60 * 1000, // 有效期
	renew: false //自动续期
}, app))

let router = new Router()
// 路由部分
const AllRoutes = require('./routes/index')
//处理405 方法不匹配 和 501 方法未实现
app.use(AllRoutes.routes(), AllRoutes.allowedMethods());
// 静态资源
_static(router, {
	html: 20
})

app.use(router.routes())

app.keys = fs.readFileSync('.keys').toString().split('\n')
app.on('error', err => {
	logger.error(err);
});
